/*
 * RealmUtils.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.utils;

import android.content.Context;

import com.yidiandao.business.data.realm.BrowingHistoryBean;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

/**
 * 建立数据库
 */
public class RealmUtils {
    /**
     * 操作浏览记录的realm
     */
    public static Realm getHistoryRealm(Context context) {
        RealmConfiguration myConfig =
                new RealmConfiguration.Builder(context)
                        .encryptionKey(new byte[64]) //加密用字段,不是64位会报错
                        .name("browingHistory.realm")
                        .schemaVersion(5)
                        /* .migration(new RealmMigration() {
                            @Override
                            public void migrate(DynamicRealm realm, long oldVersion, long
                            newVersion) {
                                RealmSchema schema = realm.getSchema();
                                //数据库版本升级
                                if (oldVersion == 1) {
                                    schema.get("BrowingHistoryBean")
                                            .addField("goods_brand", String.class);
                                    oldVersion++;
                                }
                            }
                        })*/
                        .deleteRealmIfMigrationNeeded() //暴力删除之前的
                        .build();

        return Realm.getInstance(myConfig);
    }

    /**
     * 清除个人中心的浏览历史
     */
    public static void clearBrowsingHistory(Context context) {
        Realm realm = RealmUtils.getHistoryRealm(context);
        final RealmResults<BrowingHistoryBean> results =
                realm.where(BrowingHistoryBean.class).findAll();
        realm.executeTransaction(
                new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        results.deleteAllFromRealm();
                    }
                });
    }

}
